# -*- coding: utf-8 -*-
# @Time    : 2021/9/10 13:43
# @Author  : Flora.Chen
# @File    : export_issue.py
# @Software: PyCharm
# @Desc: 导出仓库中的易修
import os.path

from common.helper import download_img, create_dir
from common.handle_excel import HandleExcel
from requests import request
from loguru import logger
import math
from common.handle_time import now
import re


def get_data(url, cookies):
    """
    获取指定易修的相关数据
    :param url: url地址
    :param cookies: 登录的cookies信息
    """
    logger.debug(f"正在获取该页的易修：{url}")
    try:
        return request(url=url, method="GET", cookies=cookies, verify=False).json()
    except Exception as e:
        logger.debug(f"获取易修相关信息报错：{e}")
        return {"error": f"{e}"}


def get_data_detail(url, cookies):
    """
    获取易修详情页数据
    :param url: url地址
    :param cookies: 登录的cookies信息
    """
    logger.debug(f"正在查看该易修：{url}")
    try:
        return request(url=url, method="GET", cookies=cookies, verify=False).json()
    except Exception as e:
        logger.debug(f"查看易修详情页报错：{e}")
        return {"error": f"{e}"}


def get_img_url(text: str):
    """
    获取图片的url地址
    :params: text 能匹配到图片地址的字符串
    """
    pattern = r"/api/attachments/(\d+)"
    urls = []
    for i in re.findall(pattern=pattern, string=text):
        urls.append("/api/attachments/" + i)
    return urls


def prepare_excel(name):
    """
    创建一个目录，创建一个excel存放数据
    :params: name 目录名称，excel名称
    """
    # 新建一个文件夹存放issue
    if not isinstance(name, str):
        name = str(name)

    # 使用传入的名称+当前时间作为目录名以及excel文件名
    issue_dir_name = f"{name}{now}"

    # 获取当前文件所在的目录
    current_dir = os.path.dirname(os.path.abspath(__file__))

    # 如果当前目录下以及存在相同名称的目录，则不创建
    issue_dir = os.path.join(current_dir, issue_dir_name)
    create_dir(issue_dir)

    # 创建execel
    excel = HandleExcel(issue_dir)
    excel_name = f"{issue_dir_name}.xlsx"
    excel.create_excel(excel_name)
    return issue_dir


def get_excel(**kwargs):
    """
    导出易修
    """
    # 获取总页数
    page_count = 15
    page = 1
    result = get_data(
        url=kwargs.get("base_url") + "/api/" + kwargs.get("repository") + "/issues.json?page=" + str(
            page) + "&limit=" + str(page_count),
        cookies=kwargs.get("cookies"))
    total = result["search_count"]
    total_page = math.ceil(int(total) / 15)

    # 准备一个目录存放excel以及新建excel
    issue_dir = prepare_excel(name=kwargs.get("repository").replace("/", "_"))
    image_path = os.path.join(issue_dir, "images")
    create_dir(image_path)

    row = 1
    while True:
        # 根据总页数，分别去请求每一页，获取每一页的结果
        for i in range(1, total_page + 1):
            # 获取当前页所有的issue
            issues = get_data(
                url=kwargs.get("base_url") + "/api/" + kwargs.get("repository") + "issues.json?page=" + str(
                    i) + "&limit=" + str(page_count),
                cookies=kwargs.get("cookies"))["issues"]

            # 循环遍历当前页的issue保存到excel中
            for issue in issues:
                logger.debug("--------------START--------------")
                data = {
                    "ID": "",
                    "issue_id": issue["id"],
                    "title": issue["name"],
                    "priority": issue["priority"],
                    "status": issue["issue_status"],
                    "assignee": issue["assign_user_name"],
                    "reporter": issue["author_name"],
                    "create_time": issue["format_time"],
                    "update_time": issue["updated_at"]
                }
                content = get_data_detail(
                    url=kwargs.get("base_url") + "/api/" + kwargs.get("repository") + "issues/" + str(
                        data["issue_id"]) + ".json",
                    cookies=kwargs.get("cookies"))
                data["description"] = content["description"],

                # 下载图片
                text = str(data["description"])
                for i in get_img_url(text):
                    path = os.path.join(image_path, data["title"] + f"_{i.replace('/', '')}.png")
                    logger.debug(f"开始下载图片， 图片绝对路径: {path}")
                    download_img(url=kwargs.get("base_url") + i, path=path)

                # 往excel中写入表头
                # 想要一个更好的方法，未完待续
                # logger.debug(f"开始写入第{row + 1}行数据")
                # excel.write(row=row + 1, column=1, data=row)
                # excel.write(row=row + 1, column=2, data=title)
                # excel.write(row=row + 1, column=3, data=description)
                # excel.write(row=row + 1, column=4, data=priority)
                # excel.write(row=row + 1, column=5, data=create_time)
                # excel.write(row=row + 1, column=6, data=update_time)
                # excel.write(row=row + 1, column=7, data=status)
                # excel.write(row=row + 1, column=8, data=developer)
                # excel.write(row=row + 1, column=9, data=tester)
                # row += 1
                # logger.debug(f"已完成了{row}行的数据写入， 易修ID： {issue_id} ")
                logger.debug("--------------END--------------")
                row = 5
        if row >= total:
            break


if __name__ == '__main__':
    from api.login_api import TrustieLogin

    base_url = "https://*******.trustie.net"
    login = TrustieLogin(base_url).login_api(user="*******", pwd="*******")
    kwargs = {
        "base_url": base_url,
        "repository": "*******/jeewx-boot/",
        "cookies": login.cookies,
        "img_path": r"*******\tools"

    }
    get_excel(**kwargs)
